package com.sky.aspect;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.sky.anno.AutoFill;
import com.sky.context.ThreadLocalUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect//声明当前类是一个切面类
@Component
public class AutoFillAspect {

    //定位到带有@AutoFill的方法
    @Pointcut("@annotation(com.sky.anno.AutoFill)")
    public void pc(){}

    //切面:前置通知
    @Before("pc()")
    public void autoFill(JoinPoint jp){
        /*
            获取切入点的参数(目标对象),给目标对象的四个字段(value属性值为insert的)或者两个字段(value值为update)设置值
         */
        //1.先获取切入点的参数(目标对象)
        Object[] args = jp.getArgs();
        if (ArrayUtil.isEmpty(args)) {
            return;
        }

        //目标对象
        Object obj = args[0];

        //2.先设置更新时间和更新人字段的值
        try {
            Field updateTimeField = getFieldByName(obj,"updateTime");
            updateTimeField.set(obj, LocalDateTime.now());

            Field updateUserField = getFieldByName(obj,"updateUser");
            updateUserField.set(obj, ThreadLocalUtil.getCurrentId());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //3.获取AutoFill注解的value属性,判断其值是否为insert,若是的话,还需要给创建时间和创建人这俩字段设置值
        //3.1获取目标方法
        MethodSignature signature = (MethodSignature) jp.getSignature();
        Method method = signature.getMethod();

        //3.2获取方法上@AutoFill注解
        AutoFill anno = method.getAnnotation(AutoFill.class);

        //3.3获取注解value属性
        String value = anno.value();

        //3.4若value为insert的时候,设置俩字段的值
        if (StrUtil.equals("insert",value)) {
            try {
                Field createTimeField = getFieldByName(obj,"createTime");
                createTimeField.set(obj, LocalDateTime.now());

                Field createUserField = getFieldByName(obj,"createUser");
                createUserField.set(obj, ThreadLocalUtil.getCurrentId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    private Field getFieldByName(Object obj, String name) throws NoSuchFieldException {
        //1.获取字节码对象
        Class clazz = obj.getClass();

        //2.通过字节码对象获取已声明指定的字段
        Field field = clazz.getDeclaredField(name);

        //3.暴力反射
        field.setAccessible(true);

        return field;
    }
}
